<?php
namespace Admin\Controller;

use Admin\Builder\AdminConfigBuilder;
use Admin\Builder\AdminListBuilder;
//use Admin\Builder\AdminTreeListBuilder;  


class BaomingController extends AdminController
{
    protected $studentModel;
    protected $classModel;

    function _initialize()
    {
        parent::_initialize();
        header("Content-Type:text/html;charset=utf-8"); 
        
        $this->classModel=D('Student/StudentClass');
        $this->gradeModel=D('Baoming/BaomingGrade');
        $this->zsModel=D('Baoming/BaomingZs');
        $this->cbsModel=D('Baoming/BaomingCbs');
        $this->classscoreModel=D('Student/StudentClassScore');
        $this->yearModel=D('Year');
        $this->termModel=D('YearTerm');
        $this->curTerm=I('term',$this->termModel->where('cur=1')->getfield('term_chj'));
        $this->curYear=I('year',$this->yearModel->where('cur=1')->getfield('year'));
        
    }
    /*设置配置项*/
        public function config()
    {
        $admin_config = new AdminConfigBuilder();

        $data = $admin_config->handleConfig();

        if (!$data) {
            $data['LIMIT_DATE'] = 1;
            $data['ZS_START_DATE'] = '2010-9-1';
            $data['ZS_END_DATE'] = '2011-8-31';
        }
         $admin_config->title('适龄儿童设置')
         ->data($data)
         ->keyRadio('LIMIT_DATE','启用适龄儿童日期设置，会自动识别超龄儿童与不足龄儿童','默认为开启，需设置起讫日期',array('1'=>'开启','0'=>'关闭'))
         ->keyDefault('LIMIT_DATE',$data['LIMIT_DATE'])
         ->keyText('ZS_START_DATE', '一年级新生起始时间，设置格式为2010-9-1')
         ->keyText('ZS_END_DATE', '一年级新生结束时间，设置格式为2011-8-31');
         $admin_config->buttonSubmit('', '保存')->display();



    }

    public function index(){
    	/**设置自动转向 **/
    	$this->redirect('config');
    }

    /*年级列表*/

      public function Grade()
    {
        $map = array('status' => 1);
        $thisModel =$this->gradeModel;
        // dump($thisModel);
        $page=I('page',1);
        $r=I('r',30);
        $totalCount=$thisModel->where($map)->count();
        
        if($totalCount){
            $list=$thisModel->where($map)
            // ->order('sort','asc')
            ->page($page, $r)
           
            ->select();
        }
       // dump($list);die;
        $this->assign('_list', $list);

        $this->meta_title = '年级列表';
        $this->display('Baoming@Admin/Gradelist');
    }
    /*年班级信息删除*/
    public function deleteGrade()
    {
        $id=I('id');
        $thisModel=$this->gradeModel;
        if ($thisModel->delete($id)){
               $this->success('删除成功。'); 
               } else {
                $this->error('删除失败。');
               }
    }
    /*年班级信息编辑*/
    public function editGrade()
    {
        $id=I('id');
        $thisModel=$this->gradeModel;

    	if(IS_POST){
    		$aGrade=$thisModel->create();
            if($id){
               if ($thisModel->save($aclass)){
               $this->success('编辑成功。'); 
               } else {
                $this->error('编辑失败。');
               }
            }else{
              if ($thisModel->add($aclass)){
               $this->success('新增成功。'); 
               } else {
                $this->error('新增失败。');
               }  
            }
    	}

    	if(!$id){
             $builder = new AdminConfigBuilder();
              $builder->title('新增年级信息')
              ->keyText('grade','年级编码')
              ->keyText('name', '年级名称')

                //->keyStatus()
                ->keyCreateTime()->keyUpdateTime()               
                ->buttonSubmit(U('Baoming/editGrade'))->buttonBack()->display();    		
    	}else{
    		$data=$thisModel->find($id);
    		 $builder = new AdminConfigBuilder();
    		  $builder->title('编辑年级信息')->keyId('id','年级ID')->keyText('grade','年级编码')
    		  ->keyText('name', '年级名称')
    		 
                //->keyStatus()
                ->keyCreateTime()->keyUpdateTime()
                ->data($data)
                ->buttonSubmit(U('Baoming/editGrade'))->buttonBack()->display();
    	}

    
    }


    public function cbslist(){
        $bj=$this->classModel->field('bj_code')->find();//获取一条班级记录

        
        $map['bj_code']=I('bj_code',$bj['bj_code']);
    	$field="*";
    	$page=I('page');

    	$builder = new AdminListBuilder();
        //$builder->clearTrash($model);
        //读取微博列表
        $map = array('status' => 1);
        
        $list = $this->cbsModel->where($map)->page($page, $r)->select();
        //dump($this->studentModel->relation(true));
        //dump($list);die;
        $totalCount = $this->cbsModel->where($map)->count();

        //显示页面

        $builder->title('插班学生基本信息')
            ->setStatusUrl(U('setStatus'))->buttonRestore()->buttonClear('Student/switch')
            ->buttonNew(U('Baoming/Index/excel_1'),'导出学生名单xlsx')
            ->keyId()->keyText('grade','年级')->keyText('name', '学生姓名')->keyText('sfz', '证件编号')
            ->keyText('lxdh1', '联系电话1')->keyText('lxdh2', '联系电话2')->keyStatus()->keyCreateTime()
            ->data($list)
            ->pagination($totalCount, $r)
            ->display();
    }
    public function zslist(){
        $bj=$this->classModel->field('bj_code')->find();//获取一条班级记录

        
        $map['bj_code']=I('bj_code',$bj['bj_code']);
        $field="*";
        $page=I('page');

        $builder = new AdminListBuilder();
        //$builder->clearTrash($model);
        //读取微博列表
        $map = array('status' => 1);
        
        $list = $this->zsModel->where($map)->page($page, $r)->select();

        $totalCount = $this->zsModel->where($map)->count();

        //显示页面

        $builder->title('一年级新生基本信息')
            ->setStatusUrl(U('setStatus'))->buttonRestore()->buttonClear('Baoming/switch')
            ->buttonNew(U('Baoming/Index/excel_1'),'导出学生名单xlsx')
            
            ->keyId()->keyText('name', '学生姓名')->keyText('sfz', '证件编号')->keyText('sex', '性别')
            ->keyText('lxdh1', '联系电话1')->keyText('lxdh2', '联系电话2')->keyStatus()->keyCreateTime()
            ->data($list)
            ->pagination($totalCount, $r)
            ->display();
    }

   

        //上传excel方法
        public function import_upload(){
        	
            if(IS_POST){
            	$config = array(
		            'maxSize'    =>   30*1024*1024, // 设置附件上传大小
		            'rootPath'   => './Uploads/',
		            'savePath'   =>     'Tmp/',// 设置附件上传目录
		            'saveName'   =>   array('uniqid'),//iconv('utf-8', 'gbk', $save),
		            'exts'       =>    array('xls', 'xlsx'),// 设置附件上传类
		            'autoSub'    =>    true,
		            'subName'    =>    array('date','Y-m'),
		            );
		        $upload = new \Think\Upload($config);// 实例化上传类

		        // 上传文件
		        $info   =   $upload->uploadOne($_FILES['excelData']);      
		        $filename = './Uploads/'.$info['savepath'].$info['savename'];
		        $exts = $info['ext'];
		        //print_r($info);exit;
		        if(!$info) {// 上传错误提示错误信息
		              $this->error($upload->getError());
		          }else{
                  // 上传成功
		           $this->student_import($filename, $exts);
		        }

            }else{
                $this->assign('meta_title','导入学生信息');
            	$this->display('Baoming@Admin/import_upload');
            }

        }
        


    /*导入数据方法*/
    protected function student_import($filename, $exts='xls')
    {
        //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
        vendor("PHPExcel"); 
        //创建PHPExcel对象，注意，不能少了\ 
        $objPHPExcel = new \PHPExcel();  
        //如果excel文件后缀名为.xls，导入这个类
        if($exts == 'xls'){
            $objReader = \PHPExcel_IOFactory::createReader('Excel5'); 

        }else if($exts == 'xlsx'){
        	$objReader = \PHPExcel_IOFactory::createReader('Excel2007');
        }
        $objReader->setReadDataOnly(true);   
        //载入文件
        $objPHPExcel = $objReader->load($filename); 
        //获取表中的第一个工作表，如果要获取第二个，把0改为1，依次类推
        $currentSheet=$objPHPExcel->getSheet(0);
        //获取总列数
        $allColumn=$currentSheet->getHighestColumn();
        //获取总行数
        $allRow=$currentSheet->getHighestRow();
        //循环获取表中的数据，$currentRow表示当前行，从哪行开始读取数据，索引值从0开始
        for($currentRow=3;$currentRow<=$allRow;$currentRow++){
            //从哪列开始，A表示第一列
            for($currentColumn='A';$currentColumn<=$allColumn;$currentColumn++){
                //数据坐标
                $address=$currentColumn.$currentRow;
                //读取到的数据，保存到数组$arr中
                $cell=$currentSheet->getCell($address)->getValue();                
                if($cell instanceof PHPExcel_RichText){//富文本转换字符串
                    $cell  = $cell->__toString();
                }
                $data[$currentRow][$currentColumn]=$cell;
                //print_r($cell);
            } 
        }
         // dump($data);exit;
        $this->save_import($data);
    }

    /*保存导入数据*/
    protected function save_import($data)
    {
         // dump($data);exit;


        $studentModel = $this->studentModel;
        foreach ($data as $k=>$v){
            
                $st_code=$v['B'];
                $info[$k]['st_code'] = $st_code;

                $st_name=trimall($v['C']);//去除学生姓名中存在的空格[extend.php]
                $info[$k]['st_name'] = $st_name;

                

                $idcard=trimall($v['E']);
                $info[$k]['sfz'] = $idcard;

                if(!idcard_checksum18($idcard)){
                 	$sex=$v['D'];
                    $info[$k]['sex']=$sex;
                 
                 }else{
                  $info[$k]['csrq']=substr($idcard, 6, 4).'-'.substr($idcard,10, 2).'-'.substr($idcard, 12, 2);
                  $info[$k]['sex']=get_xingbie($idcard);//(int)substr($idcard,16,1) % 2 === 0 ? '女':'男';//;
                 }

                $info[$k]['mobile'] = $v['F'];
                $info[$k]['mobile2'] = $v['G'];

                $bz=$v['H'];
                $info[$k]['bz'] = $bz;

                $bj_name=$v['A'];
                $stmap=array(
                	'bj_name'=>$bj_name,
                	'status'=>1,
                	);
                $bj_code = $this->classModel->where($stmap)->getField('bj_code'); 

                $info[$k]['grade']=$this->classModel->where($stmap)->getField('grade');
                //获取最后一次查询
               
                
                // dump($bj_code);exit;
                if($bj_code){
                    $info[$k]['bj_code'] = $bj_code;
                }else{
                	$info[$k]['bj_code'] = 0;//班级代号为0表示找不到
                }


                $map = array(
                	'bj_code' => $bj_code,
                	'st_name'=>$st_name,
                	'st_code'=>$st_code,
                	'status'=>1); 
                	      
                $result = $studentModel->where($map)->find();
                //dump($result);//dump($student->_sql());
                    
                  

                if($result){
                	//更新操作
                	$info[$k]['update_time']=NOW_TIME;
                    $result = $studentModel->where($map)->save($info[$k]);
                    //dump($studentModel->_sql());
                     //echo "当前操作1";  exit;
                }else{
                	//入库操作   
                     $info[$k]['create_time'] = NOW_TIME;
                     $info[$k]['update_time']=NOW_TIME;
                    //dump($info[$k-2]);//要实现自动增加自动验证需调用create函数 
                    $data=$studentModel->create($info[$k]);
                   //dump($data);echo "当前操作2";  exit;
                    $result = $studentModel->add($data);
                   // dump($studentModel->_sql()); 
                }
                //echo "当前操作";            
                //print_r($info);//exit;admin/student/studentlist
            }
       

        if(false !== $result || 0 !== $result){
            $this->success('学生导入成功', U('/Admin/Student/index'));
        }else{
            $this->error('学生导入失败');
        }
        //print_r($info);

    }


    /*编辑学年信息*/
	 public function editYear(){
	        $id=I('id',0); 
	        //判断是否在编辑模式
	        $isEdit = $id ? true : false;
	        if (IS_POST) {
	        
	        
	        $id=I('id',0);

	        //写入数据库
	        $model = $this->yearModel;
	        $data = array('year' =>I('year'), 'year_ch' =>I('year_ch','','text'),'cur'=>I('cur',0));
	        if ($isEdit) {
	            $result = $model->where(array('id' => $id))->save($data);
	        } else {
	            $result = $model->add($data);
	        }
	        //如果写入不成功，则报错
	        if ($result === false) {
	            $this->error($isEdit ? '编辑失败！' : '新增失败！');
	        }
	        //返回成功信息
	        $this->success($isEdit ? '编辑成功！' : '新增成功！');
	    } else {

	    //显示页面       
	    $builder = new AdminConfigBuilder();    
	    //判断是否在编辑模式
	    $isEdit = $id ? true : false;
	    //读取学年信息
	            if($isEdit){
	                $list=$this->yearModel->find($id);
	            }else{
	                $list=array();
	            }
	   
	    
	    $builder->title($isEdit ? '学年信息编辑':'新增学年')
	    
	    ->keyId()->keyText('year','学年','2016')->keyText('year_ch','学年（中文）','2016学年')
	    ->keyBool('cur', '当前学年', '设为当前学年')
	    ->data($list) ->buttonSubmit(U('editYear'))->buttonBack()
	    ->display();

	    }

    }
    public function editTerm(){

        $id=I('id',0); 
        //判断是否在编辑模式
        $isEdit = $id ? true : false;
        if (IS_POST) {        $id=I('id',0);

        //写入数据库
        $model = $this->termModel;
        $data = array('term' =>I('term'), 'term_ch' =>I('term_ch','','text'));
        if ($isEdit) {
            $result = $model->where(array('id' => $id))->save($data);
        } else {
            $result = $model->add($data);
        }
        //如果写入不成功，则报错
        if ($result === false) {
            $this->error($isEdit ? '编辑失败！' : '新增失败！');
        }
        //返回成功信息
        $this->success($isEdit ? '编辑成功！' : '新增成功！');
            } else {

        //显示页面       
        $builder = new AdminConfigBuilder();    
        //判断是否在编辑模式
        $isEdit = $id ? true : false;
        //读取学年信息
            if($isEdit){
                $list=$this->yearModel->find($id);
            }else{
                $list=array();
            }
        $builder = new AdminConfigBuilder();
        
       
        $list=$this->termModel->find($id);
        $builder->title('学期信息编辑')
        
        ->keyId()->keyText('term','学期','2016')
        ->keyText('term_ch','学期（中文）','2016学期第1学期')
        ->keyText('term_chj','学期（短中文）','2016上')
        ->keyText('sort','排序')
        ->keyBool('cur', '当前学期', '设为当前学期')
        ->data($list) ->buttonSubmit(U('editTerm'))->buttonBack()
       ->display();
        }

    }
     /*学年管理*/
     public function setYear(){

       // $this->meta_title = '学年管理';
        $builder = new AdminListBuilder();
        $attr1=array(
            'class' =>'btn ajax-post btn-success'
            );
        // 记录当前列表页的cookie
        Cookie('__forward__',$_SERVER['REQUEST_URI']);
        $list=$this->yearModel->order('sort asc')->select();
        $builder->title('学年管理')
        ->buttonNew(U('Baoming/editYear'))        
        ->buttonDeleteTrue(U('Baoming/deleteYear'))
        ->buttonDelete(U('Baoming/deleteYear'),'删除')
        ->buttonSort(U('Baoming/sortYear'),'排序',array('class' =>'btn btn-success'))
        // ->buttonSort(U('Baoming/sortYear'),'排序',array('class' = >'btn ajax-post btn-success'))
        ->keyId()->keyText('sort',L('排序'))
        ->keyText('year','学期')
        ->keyText('year_ch','学期（中文）')
        ->keyBool('cur', '当前学年')
        ->keyDoAction('setcurYear?id=###','设为当前学年')
        ->keyDoActionEdit('editYear?id=###','编辑')
        ->keyDoAction('deleteYear?ids=###',"删除")
        ->data($list) 
        ->display();
        
    }
        /**
     * 学年排序
     * @author shuiyueju <singliang@163.com>
     */
    public function sortYear(){
        $model=$this->yearModel;
        if(IS_GET){
            $ids = I('get.ids');
            // $pid = I('get.pid');

            //获取排序的数据
            $map = array('status'=>array('gt',-1));
            $map['hide']=0;
            if(!empty($ids))$map['id'] = array('in',$ids);

            $list = $model->where($map)->field('id,year_ch as title')->order('sort asc,id asc')->select();

            $this->assign('list', $list);
            $this->meta_title = '学年排序';
            $this->subnav=U('Baoming/setYear');//菜单高亮
            $this->display('Baoming@Admin/sort');
        }elseif (IS_POST){
            $ids = I('post.ids');
            
            $ids = explode(',', $ids);
            
            foreach ($ids as $key=>$value){
                $res = $model->where(array('id'=>$value))->setField('sort', $key+1);
            }
            if($res !== false){
                $this->success('排序成功！');
            }else{
                $this->error('排序失败！',U('sortYear'));
            }
        }else{
            $this->error('非法请求');
        }
    }
            /**
     * 学年排序
     * @author shuiyueju <singliang@163.com>
     */
    public function sortTerm(){
        $model=$this->termModel;
        if(IS_GET){
            $ids = I('get.ids');
            // $pid = I('get.pid');

            //获取排序的数据
            $map = array('status'=>array('gt',-1));
            //$map['hide']=0;
            if(!empty($ids))$map['id'] = array('in',$ids);

            $list = $model->where($map)->field('id,term_ch as title')->order('sort asc, id asc')->select();

            $this->assign('list', $list);
            $this->meta_title = '学年排序';
            $this->subnav=U('Baoming/setYearTerm');//菜单高亮
            $this->display('Baoming@Admin/sort');
        }elseif (IS_POST){
            $ids = I('post.ids');
            $ids = explode(',', $ids);
            foreach ($ids as $key=>$value){
                $res =$model->where(array('id'=>$value))->setField('sort', $key+1);
            }
            if($res !== false){
                $this->success('排序成功！');
            }else{
                $this->error('排序失败！');
            }
        }else{
            $this->error('非法请求');
        }
    }
        /*设为当前学年*/
    public function setcurYear($id){
        $aId = I('id', 0, 'intval');
        //$aId=0;
        $map['cur']=1;
        $model=$this->yearModel;
        $model->where($map)->setField(array('cur'=>0));
        $result = $model
        ->where(array('id'=>$aId))
        ->setField($map);
                //如果写入不成功，则报错
        if ($result === false) {
            $this->error($model->getError());
        }
       
        $this->success('设定成功！',U('setYear'));
    }

    /*设为当前学期*/
    public function setcurTerm($id){
        $aId = I('id', 0, 'intval');
        $map['cur']=1;
        $model=$this->termModel;
        $model->where($map)->setField(array('cur'=>0));
        $result = $model->where(array('id'=>$aId))->setField($map);
        //如果写入不成功，则报错
        if ($result === false) {
            $this->error($model->error());
        }
        $this->success('设定成功！',U('setYearTerm'));
    }


    
    /*学期管理*/
    public function setYearTerm(){
        // 记录当前列表页的cookie
        Cookie('__forward__',$_SERVER['REQUEST_URI']);
        $builder = new AdminListBuilder();
        $list=M('yearTerm')->select();
        $builder->title('学期管理')
            ->buttonNew(U('Baoming/editTerm'))
             ->buttonDeleteTrue(U('Baoming/deleteTerm'))
             ->buttonDelete(U('Baoming/deleteTerm'))
             // ->ajaxButton(U('Baoming/deleteTerm'),'','删除')
             ->buttonSort(U('Baoming/sortTerm'))
            ->keyId()
            ->keyText('sort',L('排序'))
            ->keyText('term','学期')->keyText('term_ch','学期（中文）')
            ->keyText('term_chj','学期（短中文）')
            ->keyBool('cur', '当前学期', 'text')
            ->keyDoAction('setcurTerm?id=###','设为当前学期')
            ->keyDoActionEdit('editTerm?id=###')
            
            ->keyDoAction('Baoming/deleteTerm?ids=###','删除')
           
            ->data($list) 
            ->display();
    }

    /**删除学年*/
    public function deleteYear($ids){
        !is_array($ids)&&$ids=explode(',',$ids);
        $map['id'] = array('in', $ids);
        $model=$this->yearModel;
        $res = $model->where($map)->delete();
        if($res){
            $this->success('删除成功',U('Baoming/setYear'));
        }else{
            $this->error('删除失败'.$model->getError());
        }
    }
    /**删除学期*/
    public function deleteTerm($ids){
        !is_array($ids)&&$ids=explode(',',$ids);
        $map['id'] = array('in', $ids);
        $model=$this->termModel;
        $res = $model->where($map)->delete();
        if($res){
            $this->success('删除成功',U('Baoming/setYearTerm'));
        }else{
            $this->error('删除失败'.$model->getError());
        }


    }


}